﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ClimateChangeChampionsCustomAdmin
{
    public partial class SendEmails : Acms.AcmsControls.ContentControls.Admin.BaseCustomAdminControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            dsUsers.SelectData += new EventHandler<Acms.DataControls.SelectEventArgs<Acms.Bll.User>>(dsUsers_SelectData);
            btnSend.Click += new EventHandler(btnSend_Click);
            if(!IsPostBack)
            {
                if (Request.QueryString["Debug"] != null)
                {
                    Debug = true;
                }
            }
        }

        public bool Debug { get; set; }
        protected override object SaveViewState()
        {
            ViewState["Debug"] = Debug;
            return base.SaveViewState();
        }

        protected override void LoadViewState(object savedState)
        {
            base.LoadViewState(savedState);
            if(ViewState["Debug"] is bool)
            {
                Debug = (bool)ViewState["Debug"];
            }
        }

        private const string EmailPath = "~/Emails/SiteLaunchEmail.xml";

        void btnSend_Click(object sender, EventArgs e)
        {
            foreach(Acms.Bll.User u in GetUsersRequiringEmails() )
            {
                Acms.Bll.Email email = Acms.Bll.Email.CreateInstance(u, Server.MapPath(EmailPath));
                email.Send();
            }
            grid.DataBind();
        }

        void dsUsers_SelectData(object sender, Acms.DataControls.SelectEventArgs<Acms.Bll.User> e)
        {
            e.SetData(GetUsersRequiringEmails()); 
        }

        private List<Acms.Bll.User> GetUsersRequiringEmails()
        {
            if (Debug)
            {
                List<Acms.Bll.User> data = new List<Acms.Bll.User>();
                Acms.Bll.User tmp = Acms.Bll.User.GetByEmailAddress("ollyarmfelt@gmail.com", AcmsSite.Id);
                Acms.Bll.User tmp2 = Acms.Bll.User.GetByEmailAddress("t.armfelt@gmail.com", AcmsSite.Id);

                if(tmp != null)
                    data.Add(tmp);
                if (tmp2 != null)
                    data.Add(tmp2);
                return data;
            }
            else
            {
                List<Acms.Bll.User> users = Acms.Bll.User.Search(AcmsSite.Id);
                List<Acms.Bll.User> data = new List<Acms.Bll.User>();

                foreach(Acms.Bll.User u in users)
                {
                    List<Acms.Bll.Email> emails = Acms.Bll.Email.GetAllByUserIdAndFilePath(u.Id, Server.MapPath(EmailPath));
                    if (emails.Count == 0)
                    {
                        data.Add(u);
                    }
                }
                return data;
            }
        }
    }
}